# -*- coding: utf-8 -*-

import tornado.ioloop
from tornado import gen
from tornado.concurrent import Future
from tornado.httpclient import HTTPClient, AsyncHTTPClient

def synchronous_fetch(url):
    http_client = HTTPClient()
    response = http_client.fetch(url)
    print response.headers

def asynchronous_fetch(url):
    http_client = AsyncHTTPClient()
    def callback(res):
        print res.headers
    http_client.fetch(url, callback=callback)

def async_fetch_future(url):
    client = AsyncHTTPClient()
    myf = Future()
    fetch_future = client.fetch(url)
    fetch_future.add_done_callback(
            lambda f: myf.set_result(f.result))
    import pdb; pdb.set_trace()
    print myf.result

@gen.coroutine
def fetch_coroutine(url):
    client = AsyncHTTPClient()
    res = yield client.fetch(url)
    import pdb; pdb.set_trace()
    print res.body
    with open('baidu.html', 'w') as f:
        f.write(res.body)
    raise gen.Return(res.body)

@gen.coroutine
def divide(x, y):
    print x, y
    return x / y


@gen.coroutine
def good_call():
    yield divide(1, 0)


if __name__ == '__main__':
    url = 'http://www.baidu.com'
    print good_call()
    # divide(1, 0)
    # synchronous_fetch(url)
    asynchronous_fetch(url)
    # async_fetch_future(url)
    # fetch_coroutine(url)
    # tornado.ioloop.IOLoop.current().start()
    # tornado.ioloop.IOLoop.current().run_sync(lambda: divide(1, 0))
